import redis

from configs.settings import flask_config
from utils.crypto import Crypt

redis_config = flask_config.redis_config
my_crypt = Crypt()
# password = my_crypt.decrypt(redis_config.get('password'))


class OPRedis:
    def __init__(self, db=None):
        if not hasattr(OPRedis, "pool"):
            OPRedis.get_redis_conn(db)
        self.conn = redis.Redis(connection_pool=OPRedis.pool, decode_responses=True)
        self._sub = "course_sub"

    @staticmethod
    def get_redis_conn(db):
        OPRedis.pool = redis.ConnectionPool(
            host=redis_config.get("host"),
            port=redis_config.get("port"),
            password=redis_config.get("password"),
            db=db,
        )

    """string"""

    def set_value(self, name, time, value):
        if time:
            res = self.conn.setex(name, time, value)
        else:
            res = self.conn.set(name, value)
        return res

    def get_value(self, key):
        try:
            res = self.conn.get(key).decode()
            return res
        except Exception as e:  # noqa
            return ""

    def del_value(self, key):
        res = self.conn.delete(key)
        return res

    """hash"""

    def set_hash_value(self, name, key, value):
        res = self.conn.hset(name, key, value)
        return res

    def get_hash_value(self, name, key=None):
        if key:
            res = self.conn.hget(name, key)
        else:
            res = self.conn.hgetall(name)
        return res

    def del_hash_value(self, name, key=None):
        if key:
            res = self.conn.hdel(name, key)
        else:
            res = self.conn.delete(name)
        return res

    """list"""

    def set_list_value(self, key, *args):
        res = self.conn.lpush(key, *args)
        return res

    def get_list_value(self, key, start, stop):
        res = self.conn.lrange(key, start, stop)
        return [_.decode() for _ in res]

    def del_list_value(self, key, start, stop):
        res = self.conn.ltrim(key, start, stop)
        return res


if __name__ == "__main__":
    opr = OPRedis()
    opr.set_value("test", 60, "hh")
    res = opr.get_value("test")
    print(res)
